package com.lhlk.初始化;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class 通过反射获取方法 {
    public static void main(String[] args) {
        try {
            Class aClass = Class.forName("com.lhlk.初始化.User");
            User user = (User) aClass.newInstance();
            //通过反射获取方法
            Method setAge = aClass.getDeclaredMethod("setAge", Integer.class);
            //invoke激活的意思
            setAge.invoke(user,2);
            System.out.println(user.getAge());

            System.out.println("============================");
            //通过反射操作属性
            Field name = aClass.getDeclaredField("name");

            //不能直接操作私有属性，要关闭程序的安全检测
            name.setAccessible(true);

            name.set(user,"莉丝");
            System.out.println(user.getName());



        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
